﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text.RegularExpressions;
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Sw.Hospital.HealthExaminationSystem.Application.Company.Dto;
using Sw.Hospital.HealthExaminationSystem.Application.GroupReport.Dto;
using Sw.Hospital.HealthExaminationSystem.Application.OccGroupReport.Dto;
using Sw.Hospital.HealthExaminationSystem.Common.Enums;
using Sw.Hospital.HealthExaminationSystem.Common.Helpers;
using Sw.Hospital.HealthExaminationSystem.Core.Coding;
using Sw.Hospital.HealthExaminationSystem.Core.Company;
using Sw.Hospital.HealthExaminationSystem.Core.Examination;
using Sw.Hospital.HealthExaminationSystem.Core.Occupational;
using Sw.Hospital.HealthExaminationSystem.UserException.Verification;

namespace Sw.Hospital.HealthExaminationSystem.Application.GroupReport
{
    [AbpAuthorize]
    public class GroupReportAppService : MyProjectAppServiceBase, IGroupReportAppService
    {
        #region 接口和引用
        private readonly IRepository<TjlClientInfo, Guid> _tjlClientInfo; //单位查询

        private readonly IRepository<TjlClientReg, Guid> _tjlClientReg; //预约查询
        private readonly IRepository<TjlClientTeamRegitem, Guid> _Regitem; //单位分组登记项目
        private readonly IRepository<TjlCustomerReg, Guid> _cusReg; //体检预约
        private readonly IRepository<TjlCustomerSummarizeBM, Guid> _cusSummarizeBM; //体检预约
        private readonly IRepository<TjlCustomerReg, Guid> _CustomerReg; //体检预约
        private readonly IRepository<TjlCustomerRegItem, Guid> _CustomerRegItem; //检查结果
        private readonly IRepository<TjlCusReview, Guid> _TjlCusReview; //检查结果 
        private readonly IRepository<TjlOccCustomerHazardSum, Guid> _CustomerHazardSum; //检查结果 
        private readonly IRepository<TjlClientTeamInfo, Guid> _TjlClientTeamInfo; //单位分组 

        private readonly IRepository<TbmOccTargetDisease, Guid> _TbmOccTargetDisease; //目标疾病 

        private readonly IRepository<TjlCustomerDepSummary, Guid> _CustomerDepSummary; //科室小结 
        private readonly IRepository<TbmBasicDictionary, Guid> _BasicDictionary; //字典表 

        public GroupReportAppService(
            IRepository<TjlClientReg, Guid> tjlClientReg,
            IRepository<TjlClientInfo, Guid> tjlClientInfo,
            IRepository<TjlClientTeamRegitem, Guid> Regitem,
             IRepository<TjlCustomerReg, Guid> CusReg,
             IRepository<TjlCustomerSummarizeBM, Guid> CusSummarizeBM,
             IRepository<TjlCustomerReg, Guid> CustomerReg,
             IRepository<TjlCustomerRegItem, Guid> CustomerRegItem,
             IRepository<TjlCusReview, Guid> TjlCusReview,
             IRepository<TjlOccCustomerHazardSum, Guid> TjlOccCustomerSum,
             IRepository<TjlClientTeamInfo, Guid> TjlClientTeamInfo, //单位分组 
             IRepository<TbmOccTargetDisease, Guid>  OccTargetDisease,
             IRepository<TjlCustomerDepSummary, Guid> CustomerDepSummary,
            IRepository<TjlClientTeamInfo, Guid> ClientTeamInfo,
            IRepository<TbmBasicDictionary, Guid> BasicDictionary


        )
        {
            _tjlClientReg = tjlClientReg;
            _tjlClientInfo = tjlClientInfo;
            _Regitem = Regitem;
            _cusReg = CusReg;
            _cusSummarizeBM = CusSummarizeBM;
            _CustomerReg = CustomerReg;
            _CustomerRegItem = CustomerRegItem;
            _TjlCusReview = TjlCusReview;
            _CustomerHazardSum = TjlOccCustomerSum;
            _TjlClientTeamInfo = ClientTeamInfo;
            _TbmOccTargetDisease = OccTargetDisease;
            _CustomerDepSummary = CustomerDepSummary;
            _BasicDictionary = BasicDictionary;
        }
        #endregion

        /// <summary>
        /// 单位查询
        /// </summary>
        public List<SelectClientRewDto> QueryCompany()
        {

            var PaDtoList = _tjlClientReg.GetAllIncluding(r => r.ClientInfo);
            var rows = PaDtoList.OrderByDescending(o => o.CreationTime).MapTo<List<SelectClientRewDto>>();
            return rows;
        }

        /// <summary>
        /// 单位按名称查询
        /// </summary>
        public List<SelectClientRewDto> QueryCompanyName(SelectClientRewDto input)
        {
            var query = _tjlClientReg.GetAllIncluding(r => r.ClientInfo);
            //单位ID
            if (input.ClientInfo != null)
            {
                query = query.Where(o => o.ClientInfo.Id == input.ClientInfo.Id);
            }
            if (input.ClientRegStart != null && input.ClientRegEnd != null)
            {
                query = query.Where(o => o.StartCheckDate <= input.ClientRegEnd && o.StartCheckDate > input.ClientRegStart);
            }

            return query.MapTo<List<SelectClientRewDto>>();
        }

        /// <summary>
        /// 分组/人员查询
        /// </summary>
        public List<List<GroupClientRegDto>> QueryGroup(List<GroupClientRegDto> input)
        {
            List<List<GroupClientRegDto>> regDtos = new List<List<GroupClientRegDto>>();
            //List<GroupClientRegDto> dto = new List<GroupClientRegDto>();

            foreach (var item in input)
            {
                var query = _tjlClientReg.GetAll();
                query = query.Where(o => o.ClientInfo.Id == item.ClientInfo.Id);
                var rows = query.MapTo<List<GroupClientRegDto>>();
                regDtos.Add(rows);
            }


            return regDtos;
        }
        /// <summary>
        /// 获取单位下组合项目信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns> 
        public List<GroupClientItemsDto> GRClientRegItems(ClientRegIdDto input)
        {
            List<GroupClientItemsDto> tjlClientTeamRegitems = new List<GroupClientItemsDto>();
            var query = _Regitem.GetAll();
            query = query.Where(o => input.Idlist.Contains(o.ClientRegId.Value) && o.Department.Category != "耗材").OrderBy(o => o.ClientTeamInfo.TeamBM).ThenBy(o => o.DepartmentOrder).ThenBy(o => o.ItemGroupOrder);

            tjlClientTeamRegitems = query.MapTo<List<GroupClientItemsDto>>();
            return tjlClientTeamRegitems;
        }

        /// <summary>
        /// 获取单位下人员
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public List<GroupClientCusDto> GRClientRegCus(ClientRegIdDto input)
        {
            List<GroupClientCusDto> tjlClientCus = new List<GroupClientCusDto>();
            var query = _cusReg.GetAll().AsQueryable();
            //query = query.Where(o =>o.ReviewSate!=2 && input.Idlist.Contains(o.ClientRegId.Value) );
            query = query.Where(o => input.Idlist.Contains(o.ClientRegId.Value));
            if (input.CusRegIds != null && input.CusRegIds.Count > 0)
            {
                var clienregID = input.Idlist.First();
                query = query.Where(o =>  o.ClientRegId== clienregID && input.CusRegIds.Contains(o.Id));
            }
            tjlClientCus = query.MapTo<List<GroupClientCusDto>>();
            return tjlClientCus;

        }

        /// <summary>
        /// 获取单位下人员
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public List<SimGroupClientCusDto> GRClientRegCusSmp(ClientRegIdDto input)
        {
            List<SimGroupClientCusDto> tjlClientCus = new List<SimGroupClientCusDto>();
            var query = _cusReg.GetAll().AsQueryable();
            query = query.Where(o => input.Idlist.Contains(o.ClientRegId.Value));
            tjlClientCus = query.Select(o => new SimGroupClientCusDto
            {
                Id = o.Id,
                Age = o.Customer.Age,
                AgeUnit = o.Customer.AgeUnit,
                BookingDate = o.BookingDate,
                CustomerBM = o.CustomerBM,
                LoginDate = o.LoginDate,
                Name = o.Customer.Name,
                PostState = o.PostState,
                Sex = o.Customer.Sex == 1 ? "男" : "女",
                TjlClientReg_Id = o.ClientRegId.Value,
                ClientTeamInfoId = o.ClientTeamInfoId,
                PhysicalType = o.PhysicalType,
                TeamName = o.ClientTeamInfo.TeamName,
                SummSate = o.SummSate
            }).ToList();
            return tjlClientCus;

        }
        /// <summary>
        /// 获取单位下人员
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public List<SimGroupClientCusDto> GRClientRegCusBM(CusRegBMDto input)
        {
            List<SimGroupClientCusDto> tjlClientCus = new List<SimGroupClientCusDto>();
            var query = _cusReg.GetAll().AsQueryable();
            query = query.Where(o => input.BMlist.Contains(o.CustomerBM));
            tjlClientCus = query.Select(o => new SimGroupClientCusDto
            {
                Id = o.Id,
                Age = o.Customer.Age,
                AgeUnit = o.Customer.AgeUnit,
                BookingDate = o.BookingDate,
                CustomerBM = o.CustomerBM,
                LoginDate = o.LoginDate,
                Name = o.Customer.Name,
                PostState = o.PostState,
                Sex = o.Customer.Sex == 1 ? "男" : "女",
                TjlClientReg_Id = o.ClientRegId.Value,
                ClientTeamInfoId = o.ClientTeamInfoId,
                PhysicalType = o.PhysicalType,
                TeamName = o.ClientTeamInfo.TeamName
            }).ToList();
            return tjlClientCus;

        }
        /// <summary>
        /// 获取单位下总检建议
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public List<GroupClientSumDto> GRClientCusSum(ClientRegIdDto input)
        {
            var sumzd = _BasicDictionary.FirstOrDefault(p => p.Type == BasicDictionaryType.GroupReportSet.ToString() && p.Value == 22)?.Remarks;

            List<GroupClientSumDto> tjlClientCus = new List<GroupClientSumDto>();
            var query = _cusSummarizeBM.GetAll().Where(o => o.CustomerReg.ReviewSate != 2 && !o.SummarizeName.Contains("未见异常") &&
            !o.SummarizeName.Contains("未见明显异常") &&
            !o.SummarizeName.Contains("温馨提示"));
            query = query.Where(o => input.Idlist.Contains(o.CustomerReg.ClientRegId.Value));
            tjlClientCus = query.MapTo<List<GroupClientSumDto>>();
            var tjlClientCus1 = tjlClientCus.Select(o => new GroupClientSumDto
            {
                Advice = o.Advice,
                CustomerReg = o.CustomerReg,
                CustomerRegID = o.CustomerRegID,
                Id = o.Id,
                SummarizeAdvice = o.SummarizeAdvice,
                SummarizeAdviceId = o.SummarizeAdviceId,
                SummarizeName =(!string.IsNullOrEmpty(sumzd) && sumzd == "1") ? o.SummarizeName.Replace("\r\n", "").Replace("\r", "").Replace("\n", "") : o.SummarizeName.Replace(" ", "").Replace("\r\n", "").Replace("\r", "").Replace("\n", ""),
                SummarizeOrderNum = o.SummarizeOrderNum,
                SummarizeType = o.SummarizeType,
                IsPrivacy = o.IsPrivacy  

            }).ToList();
            #region 时珍堂总检拆分合并
            if (!string.IsNullOrEmpty(sumzd) && sumzd == "1")
            {
                List<GroupClientSumDto> newList = new List<GroupClientSumDto>();
                List<GroupClientSumDto> REmoveList = new List<GroupClientSumDto>();
             
                #region 用空格差分处理
                foreach (var cusSum in tjlClientCus1)
                {
                    string summ = cusSum.SummarizeName;

                    if (cusSum.SummarizeName.Replace("（", "(").Replace("）", ")").Trim().EndsWith(")") && cusSum.SummarizeName.Replace("（", "(").Replace("）", ")").Contains("("))
                    {
                        summ = cusSum.SummarizeName.Substring(0, cusSum.SummarizeName.Replace("（", "(").Replace("）", ")").IndexOf('('));
                    }


                    var sum = summ.Replace(" ", "&");
             
                    if (!string.IsNullOrEmpty(sum) && sum.Contains("&"))
                    {
                        
                        var sumlist = sum.Split('&').Where(p => p != null && p != "").ToList();
                        foreach (string sumName in sumlist)
                        {
                            GroupClientSumDto groupClientSum = new GroupClientSumDto();
                            groupClientSum.Advice = cusSum.Advice;
                            groupClientSum.CustomerReg = cusSum.CustomerReg;
                            groupClientSum.CustomerRegID = cusSum.CustomerRegID;

                            groupClientSum.SummarizeAdvice = cusSum.SummarizeAdvice;
                            groupClientSum.SummarizeAdviceId = cusSum.SummarizeAdviceId;
                            groupClientSum.SummarizeName = sumName;
                            groupClientSum.SummarizeOrderNum = cusSum.SummarizeOrderNum;
                            groupClientSum.SummarizeType = cusSum.SummarizeType;
                            groupClientSum.IsPrivacy = cusSum.IsPrivacy;
                            newList.Add(groupClientSum);
                        }
                        REmoveList.Add(cusSum);
                    }

                }
                
                if (newList.Count > 0)
                {
                    
                    foreach (var rem in REmoveList)
                    { tjlClientCus1.Remove(rem); }
                    tjlClientCus1.AddRange(newList);
                }
                #endregion
                #region 去掉括号合并处理
                //结尾是括号去掉括号里的内容
                List<GroupClientSumDto> cussumlist = new List<GroupClientSumDto>();
                foreach (var clientsum in tjlClientCus1)
                {
                    try
                    {
                        GroupClientSumDto groupClientSum = new GroupClientSumDto();
                        groupClientSum.Advice = clientsum.Advice;
                        groupClientSum.CustomerReg = clientsum.CustomerReg;
                        groupClientSum.CustomerRegID = clientsum.CustomerRegID;
                        groupClientSum.Id = clientsum.Id;
                        groupClientSum.SummarizeAdvice = clientsum.SummarizeAdvice;
                        groupClientSum.SummarizeAdviceId = clientsum.SummarizeAdviceId;
                        groupClientSum.SummarizeName = clientsum.SummarizeName;
                        groupClientSum.SummarizeOrderNum = clientsum.SummarizeOrderNum;
                        groupClientSum.SummarizeType = clientsum.SummarizeType;
                        groupClientSum.IsPrivacy = clientsum.IsPrivacy;
                        if (clientsum.SummarizeName.Replace("（", "(").Replace("）", ")").Trim().EndsWith(")") && clientsum.SummarizeName.Replace("（", "(").Replace("）", ")").Contains("("))
                        {
                            var ss = clientsum.SummarizeName.Substring(0, clientsum.SummarizeName.Replace("（", "(").Replace("）", ")").IndexOf('('));
                            groupClientSum.SummarizeNameGroup = ss;
                        }
                        else
                        {
                            groupClientSum.SummarizeNameGroup = clientsum.SummarizeName;
                        }
                        cussumlist.Add(groupClientSum);
                    }
                    catch (Exception ex)
                    {

                        
                    }
                }
              
                //var cussumlist = tjlClientCus1.Select(o => new
                // GroupClientSumDto
                //{
                //    Advice = o.Advice,
                //    CustomerReg = o.CustomerReg,
                //    CustomerRegID = o.CustomerRegID,
                //    Id = o.Id,
                //    SummarizeAdvice = o.SummarizeAdvice,
                //    SummarizeAdviceId = o.SummarizeAdviceId,
                //    SummarizeName = o.SummarizeName,
                //    SummarizeOrderNum = o.SummarizeOrderNum,
                //    SummarizeType = o.SummarizeType,
                //    IsPrivacy = o.IsPrivacy,
                //    SummarizeNameGroup = o.SummarizeName.Replace("（","(").Replace("）",")").Trim().EndsWith(")")? o.SummarizeName.Replace("（", "(").Replace("）", ")").Substring(0, o.SummarizeName.IndexOf('(')) : o.SummarizeName // Regex.Replace(o.SummarizeName.Replace("\r\n", ""), pattern, string.Empty)
                //}
                // ).ToList();
                var newcussumlist = cussumlist.GroupBy(p => new { p.CustomerReg, p.CustomerRegID, p.SummarizeAdviceId, p.SummarizeNameGroup }).Select(
                    p => new GroupClientSumDto
                    {
                        Advice = p.FirstOrDefault().Advice,
                        CustomerReg = p.Key.CustomerReg,
                        CustomerRegID = p.Key.CustomerRegID,
                        Id = p.FirstOrDefault().Id,
                        IsPrivacy = p.FirstOrDefault().IsPrivacy,
                        SummarizeAdvice = p.FirstOrDefault().SummarizeAdvice,
                        SummarizeAdviceId = p.FirstOrDefault().SummarizeAdviceId,
                        SummarizeName = p.Key.SummarizeNameGroup,
                        SummarizeNameGroup = p.Key.SummarizeNameGroup,
                        SummarizeOrderNum = p.FirstOrDefault().SummarizeOrderNum,
                        SummarizeType = p.FirstOrDefault().SummarizeType
                    }).ToList();
                var ss3 = cussumlist.Where(p => p.SummarizeNameGroup==null ||  p.SummarizeNameGroup == "").ToList();
                tjlClientCus1 = newcussumlist;
                #endregion
            }
            #endregion
            return tjlClientCus1;

        }
        /// <summary>
        /// 获取单位历史下总检建议
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public List<HistoryGroupClientSumDto> GRHisClientCusSum(ClientRegIdDto input)
        {
            var clientIdlist = _tjlClientReg.GetAll().Where(o => input.Idlist.Contains(o.Id)).ToList();
            var clienIds = clientIdlist.Select(p => p.ClientInfoId).ToList();



            List<HistoryGroupClientSumDto> tjlClientCus = new List<HistoryGroupClientSumDto>();
            var query = _cusSummarizeBM.GetAll().Where(o => o.CustomerReg.ReviewSate != 2 && !o.SummarizeName.Contains("未见异常") &&
            !o.SummarizeName.Contains("未见明显异常") &&
            !o.SummarizeName.Contains("温馨提示"));
            var ClientRegIds = query.Where(o => !input.Idlist.Contains(o.CustomerReg.ClientRegId.Value) &&
            clienIds.Contains(o.CustomerReg.ClientInfoId.Value)).OrderByDescending(p => p.CustomerReg.ClientReg.StartCheckDate).Select(p => p.CustomerReg.ClientRegId).Distinct().Take(2);

            var clienretIdlist = ClientRegIds.ToList();

            query = query.Where(o => clienretIdlist.Contains(o.CustomerReg.ClientRegId.Value));

            var tjlClientCus1 = query.Select(o => new HistoryGroupClientSumDto
            {
                Advice = o.Advice,
                CustomerRegID = o.CustomerRegID,


                SummarizeAdviceId = o.SummarizeAdviceId,
                SummarizeName = o.SummarizeName.Replace(" ", "").Replace("\r\n", "").Replace("\r", "").Replace("\n", ""),
                SummarizeOrderNum = o.SummarizeOrderNum,
                SummarizeType = o.SummarizeType,
                IsPrivacy = o.IsPrivacy,
                ClientRegBM = o.CustomerReg.ClientReg.ClientRegBM,
                ClientRegDate = o.CustomerReg.ClientReg.StartCheckDate,
                ClientRegId = o.CustomerReg.ClientRegId,
                Sex = o.CustomerReg.Customer.Sex
            }).ToList();
            return tjlClientCus1;

        }
        public List<SelectClientRewDto> getreglist(List<EntityDto<Guid>> input)
        {
            var ids = input.Select(o => o.Id);
            var clientreg = _tjlClientReg.GetAllIncluding(o => o.ClientInfo).Where(r => ids.Contains(r.ClientInfo.Id)).Select(o => new { o.Id, o.StartCheckDate, o.ClientInfo });
            return clientreg.MapTo<List<SelectClientRewDto>>();
        }
        /// <inheritdoc />
        [UnitOfWork(false)]
        public List<GroupClientRegDto> GetCompanyRegisterIncludeGroupAndPersonnel(EntityDto<Guid> input)
        {
            var query = _tjlClientReg.GetAllIncluding(r => r.ClientTeamInfo, r => r.ClientInfo).AsNoTracking();
            query = query.Where(r => r.ClientInfoId == input.Id);
            query = query.OrderByDescending(r => r.StartCheckDate);
            return query.MapTo<List<GroupClientRegDto>>();
        }
        /// <summary>
        /// 获取单位诊断
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public List<GroupSumBMDto> getClientSum(ClientRegIdDto input)
        {
            List<GroupSumBMDto> tjlClientCus = new List<GroupSumBMDto>();
            var query = _cusSummarizeBM.GetAll().Where(o => !o.SummarizeName.Contains("未见异常") &&
            !o.SummarizeName.Contains("未见明显异常") &&
            !o.SummarizeName.Contains("温馨提示"));
            query = query.Where(o => input.Idlist.Contains(o.CustomerReg.ClientRegId.Value));
            tjlClientCus = query.GroupBy(o => o.SummarizeName).Select(o => new GroupSumBMDto
            {
                SummarizeName = o.Key,
                cout = o.Count()
            }).OrderByDescending(o => o.cout).ToList();
            return tjlClientCus;

        }
        public List<SumClientDto> getClientSumResult(EntityDto<Guid> input)
        {
            List<SumClientDto> sumClientDtos = new List<SumClientDto>();
            string Hstr = SymbolHelper.SymbolFormatter(Symbol.High);
            string Lstr = SymbolHelper.SymbolFormatter(Symbol.Low);
            string SHstr = SymbolHelper.SymbolFormatter(Symbol.Superhigh);
            string ULstr = SymbolHelper.SymbolFormatter(Symbol.UltraLow);

            //阳性结果
            var que = _CustomerRegItem.GetAll().Where(o => o.CustomerRegBM.ClientRegId == input.Id
              && o.ProcessState == (int)ProjectIState.Complete &&
              (o.Symbol == Hstr || o.Symbol == Lstr
              || o.Symbol == SHstr || o.Symbol == ULstr)).
              Select(o => new { o.CustomerRegBM.Customer.Name, o.ItemName, o.ItemResultChar, o.CustomerRegId }).ToList();



            var query = _cusSummarizeBM.GetAll().Where(o => !o.SummarizeName.Contains("未见异常") &&
            !o.SummarizeName.Contains("未见明显异常") &&
            !o.SummarizeName.Contains("温馨提示"));
            query = query.Where(o => o.CustomerReg.ClientRegId == input.Id);
            //异常名单
            var cuslst = query.Select(o => new { o.CustomerReg.Customer.Name, o.SummarizeName, o.Advice, o.CustomerRegID }).ToList();
            var tjlClientCus = cuslst.GroupBy(o => o.SummarizeName).Select(o => new
            {
                SummarizeName = o.Key,
                advice = o.First(n => n.SummarizeName == o.Key).Advice,
                cout = o.Count()
            }).OrderByDescending(o => o.cout).ToList();
            foreach (var sum in tjlClientCus)
            {
                SumClientDto sumClientDto = new SumClientDto();
                var SumName = sum.SummarizeName.Replace("偏高", "").Replace("偏低", "").
                    Replace("极高", "").Replace("极低", "").Replace("升高", "").Replace("降低", "");
                var cusregIds = cuslst.Where(o => o.SummarizeName == sum.SummarizeName).Select(o => o.CustomerRegID).ToList();
                var cuslist = que.Where(o => SumName == o.ItemName && cusregIds.Contains(o.CustomerRegId)).Select(o => (o.Name + " " + o.ItemName + ":" + o.ItemResultChar)).ToList();
                sumClientDto.SumName = sum.SummarizeName;
                sumClientDto.SumAdvicee = sum.advice;
                if (cuslist != null && cuslist.Count > 0)
                {

                    sumClientDto.CusSum = string.Join(",", cuslist).TrimEnd(',') + "(共" + sum.cout + "人)";
                }
                else
                {
                    var sumcuslist = cuslst.Where(o => o.SummarizeName == sum.SummarizeName).Select(o => o.Name).ToList();
                    sumClientDto.CusSum = string.Join(",", sumcuslist).TrimEnd(',') + "(共" + sum.cout + "人)";
                }
                sumClientDtos.Add(sumClientDto);

            }
            return sumClientDtos;
        }

        /// <summary>
        /// 获取单位复查信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public List<CusReviewGroupDto> ReVewGroupCus(EntityDto<List<Guid>> input)
        {
            List<CusReviewGroupDto> tjlClientCus = new List<CusReviewGroupDto>();
            var query = _TjlCusReview.GetAll().AsQueryable();
            var cusSum = _CustomerHazardSum.GetAll().Where(p => p.CustomerRegBMId != null && p.CustomerRegBM != null && input.Id.Contains(p.CustomerRegBMId.Value)).ToList();
            query = query.Where(o => input.Id.Contains(o.CustomerRegId.Value));
            foreach (var cus in query)
            {
                if (cus.ItemGroup != null)
                {
                    foreach (var Group in cus.ItemGroup)
                    {
                        CusReviewGroupDto cusReviewGroup = new CusReviewGroupDto();
                        cusReviewGroup.Age = cus.CustomerReg.Customer.Age;
                        cusReviewGroup.AgeUnit = cus.CustomerReg.Customer.AgeUnit;
                        cusReviewGroup.Conclusion = cusSum.FirstOrDefault(p => p.CustomerRegBMId == cus.CustomerRegId)?.Conclusion;
                        cusReviewGroup.CustomerBM = cus.CustomerReg.CustomerBM;
                        cusReviewGroup.Department = cus.CustomerReg.Customer.Department;
                        cusReviewGroup.InjuryAge = cus.CustomerReg.InjuryAge;
                        cusReviewGroup.ItemGroupName = Group.ItemGroupName;
                        cusReviewGroup.Name = cus.CustomerReg.Customer.Name;
                        cusReviewGroup.Remart = cus.Remart;
                        cusReviewGroup.RiskS = cus.CustomerReg.RiskS;
                        cusReviewGroup.Sex = cus.CustomerReg.Customer.Sex == 1 ? "男" : "女";
                        cusReviewGroup.TypeWork = cus.CustomerReg.TypeWork;
                        tjlClientCus.Add(cusReviewGroup);
                    }
                }

            }

            return tjlClientCus;

        }
        public GroupReportMainHBDto GetGroupReportHB(HBReportInDto input)
        {
            try
            {
                GroupReportMainHBDto outPut = new GroupReportMainHBDto();

                var allperson = _CustomerReg.GetAll().Where(p => p.ClientRegId == input.Id);
                if (input.RegIds != null && input.RegIds.Count > 0)
                {
                    allperson = allperson.Where(p => input.RegIds.Contains(p.Id));
                }
                var Checkperson = _CustomerReg.GetAll().Where(p =>
                  p.ClientRegId == input.Id && p.SummSate == 4);
                if (input.RegIds != null && input.RegIds.Count > 0)
                {
                    Checkperson = Checkperson.Where(p => input.RegIds.Contains(p.Id));
                }
                #region 总人数
                var allPerson = allperson.Count();
                var checkPerson = Checkperson.Count();
                var checkMan = Checkperson.Where(p => p.Customer.Sex == 1).Count();
                var checkWomen = Checkperson.Where(p => p.Customer.Sex == 2).Count();
                outPut.ZBBRS = new List<MasterRSDto>();
                MasterRSDto masterRS = new MasterRSDto();
                var clientINfo = _tjlClientReg.FirstOrDefault(p => p.Id == input.Id);
                if (clientINfo != null)
                {
                    masterRS.ClientName = clientINfo.ClientInfo.ClientName;
                    masterRS.ClientBM = clientINfo.ClientInfo.ClientBM;
                    masterRS.StartCheckDate = clientINfo.StartCheckDate;
                }
                masterRS.MRS = checkMan;
                masterRS.WRS = checkWomen;
                masterRS.TJRS = allPerson;
                masterRS.TJWCRS = checkPerson;
                var cussum = _CustomerHazardSum.GetAll().Where(p => p.CustomerRegBM.ClientRegId == input.Id);
                if (input.RegIds != null && input.RegIds.Count > 0)
                {
                    cussum = cussum.Where(p => p.CustomerRegBMId != null && input.RegIds.Contains(p.CustomerRegBMId.Value));
                }
                var occcusSum = cussum.ToList();

                var occYSzyb = occcusSum.Where(p => p.Conclusion != null && p.Conclusion.Contains("职业病")).Select(p => p.CustomerRegBMId).Distinct().Count();
                var occYSjjz = occcusSum.Where(p => p.Conclusion != null && p.Conclusion.Contains("禁忌证")).Select(p => p.CustomerRegBMId).Distinct().Count();
                var occYSfc = occcusSum.Where(p => p.Conclusion != null && p.Conclusion.Contains("复查")).Select(p => p.CustomerRegBMId).Distinct().Count();
                var occYSqt = occcusSum.Where(o => o.Conclusion != null && (o.Conclusion.Contains("其他异常") || o.Conclusion.Contains("其他疾病"))).Select(p => p.CustomerRegBMId).Distinct().Count();
                var occYSwjyc = occcusSum.Where(o => o.Conclusion != null && (o.Conclusion.Contains("未见异常") || o.Conclusion.Contains("未见明显异常"))).Select(p => p.CustomerRegBMId).Distinct().Count();
                masterRS.ZYBRS = occYSzyb;
                masterRS.JJZRS = occYSjjz;
                masterRS.FCRS = occYSfc;
                masterRS.QTJBYC = occYSqt;
                masterRS.WJYCRS = occYSwjyc;

                outPut.ZBBRS.Add(masterRS);
                #endregion
                //车间工种人数
                #region 车间工种人数
                var sjgzrs = allperson.
                      GroupBy(p => new { p.WorkName, p.TypeWork, p.RiskS })
                      .Select(
                      p => new GZDetailDto
                      {
                          CJ = p.Key.WorkName,
                          gz = p.Key.TypeWork,
                          SJRS = p.Count(),
                          WHYS = p.Key.RiskS
                      }).ToList();
                outPut.GZRS = sjgzrs;
                #endregion
                //目标疾病
                #region 目标疾病 用每个人的，单位分组有时候保存的有问题
                //         var riskque = _TjlClientTeamInfo.GetAll().Where(p => p.ClientRegId
                //            == input.Id);
                //         List<Guid?> clientteamIds = new List<Guid?>();
                //         if (input.RegIds != null && input.RegIds.Count > 0)
                //         {
                //             clientteamIds = _CustomerReg.GetAll().Where(p => p.ClientRegId == input.Id
                //&& input.RegIds.Contains(p.Id)).Select(p => p.ClientTeamInfoId).ToList();
                //             riskque = riskque.Where(p => clientteamIds.Contains(p.Id));
                //         }
                //         var riskList = riskque.SelectMany(p => p.OccHazardFactors).Select(p => p.Id).Distinct().ToList();
                //过滤体检人的目标疾病
                var riskList = allperson.SelectMany(p => p.OccHazardFactors).Select(p => p.Id).Distinct().ToList();

                var mbjblist = _TbmOccTargetDisease.GetAll().Where(p => p.OccHazardFactorsId != null && p.OccHazardFactors != null
                && riskList.Contains(p.OccHazardFactorsId.Value)).GroupBy(p => p.OccHazardFactorsId).Select(
                    p => new
                    {
                        WHYS = p.FirstOrDefault().OccHazardFactors.Text,
                        JJZ = p.SelectMany(o => o.OccDiseases).Select(n => n.Text).Distinct().ToList(),
                        zyb = p.SelectMany(o => o.Contraindications).Select(n => n.Text).Distinct().ToList()
                    }).ToList();
                outPut.MBJB = new List<MBJBDetailDto>();
                foreach (var mbjb in mbjblist)
                {
                    MBJBDetailDto mBJBDetail = new MBJBDetailDto();
                    mBJBDetail.WHYS = mbjb.WHYS;
                    mBJBDetail.JJZ = string.Join(",", mbjb.JJZ);
                    mBJBDetail.ZYB = string.Join(",", mbjb.zyb);
                    outPut.MBJB.Add(mBJBDetail);
                }
                #endregion
                //分组检查项目
                #region 分组检查项目
                outPut.WHYSXM = new List<WHYSXMDto>();
                var fzjcxmlist = _TjlClientTeamInfo.GetAll().Where(p => p.ClientRegId
                   == input.Id).ToList();
                List<Guid?> clientteamIds = new List<Guid?>();
                if (input.RegIds != null && input.RegIds.Count > 0)
                {
                    clientteamIds = _CustomerReg.GetAll().Where(p => p.ClientRegId == input.Id
       && input.RegIds.Contains(p.Id)).Select(p => p.ClientTeamInfoId).ToList();

                }
                if (input.RegIds != null && input.RegIds.Count > 0 && clientteamIds != null && clientteamIds.Count > 0)
                {
                    fzjcxmlist = fzjcxmlist.Where(p => clientteamIds.Contains(p.Id)).ToList();
                }
                var fzitemques = _Regitem.GetAll().Where(p => p.ClientRegId == input.Id);
                if (input.RegIds != null && input.RegIds.Count > 0 && clientteamIds != null && clientteamIds.Count > 0)
                {
                    fzitemques = fzitemques.Where(p => clientteamIds.Contains(p.ClientTeamInfoId));
                }
                var fzitems = fzitemques.Select(
                    p => new { p.ClientRegId, p.ItemGroupName }).Distinct().ToList();
                foreach (var fz in fzjcxmlist)
                {
                    WHYSXMDto wHYSXM = new WHYSXMDto();
                    wHYSXM.WHYS = fz.RiskName;
                    wHYSXM.JKXM = string.Join(",", fzitems.Where(p => p.ClientRegId == fz.ClientRegId).Select(p => p.ItemGroupName));
                    outPut.WHYSXM.Add(wHYSXM);
                }
                #endregion
                //异常项目           
                #region 异常项目
                //数值型判断，科室类别是检验,显示组合
                var queycst = _CustomerRegItem.GetAll().Where(p =>
                p.CustomerRegBM.ClientRegId == input.Id && p.DepartmentBM != null
                  && ((p.DepartmentBM.Category == "检验" && p.Symbol != null
                   && p.Symbol != "" && p.Symbol != "M")
                   || ((p.ItemName.Contains("收缩压") || p.ItemName.Contains("舒张压"))
                   && p.Symbol != null && p.Symbol != "" && p.Symbol != "M")
                   )).ToList();
                if (input.RegIds != null && input.RegIds.Count > 0)
                {
                    queycst = queycst.Where(p => input.RegIds.Contains(p.CustomerRegId)).ToList();
                }
                var ycst = queycst.GroupBy(
                    p => new { p.DepartmentId, p.ItemGroupBM?.ItemGroupName, p.Symbol }).Select(
                      p => new YCXMDto
                      {
                          DepartId = p.Key.DepartmentId,
                          GroupName = p.Key.ItemGroupName,
                          IllName = p.FirstOrDefault().ItemName + (p.Key.Symbol.Contains("H") ? "偏高" : "偏低"),
                          OrderNum = p.FirstOrDefault().DepartmentBM.OrderNum,
                          Count = p.Select(o => o.CustomerRegId).Distinct().Count()
                      }).ToList();
                List<string> departnames = new List<string>();
                departnames.Add("心电图");
                departnames.Add("彩超");
                departnames.Add("胸片");
                departnames.Add("电测听");
                departnames.Add("肺功能");
                var departlist = ycst.Select(p => p.DepartId).Distinct();
                var cusSmum = _CustomerDepSummary.GetAll().Where(p => p.CustomerReg.ClientRegId == input.Id
                 && p.DepartmentBMId != null && !departlist.Contains(p.DepartmentBMId.Value)
                  && departnames.Contains(p.DepartmentName));
                if (input.RegIds != null && input.RegIds.Count > 0)
                {
                    cusSmum = cusSmum.Where(p => p.CustomerRegId != null && input.RegIds.Contains(p.CustomerRegId.Value));
                }
                List<YCXMDto> cusdepartSumlist = new List<YCXMDto>();
                //科室小结异常，显示科室名称，通过建议名称反查所在科室
                var jyyclistjb = _cusSummarizeBM.GetAll().Where(p =>
               p.CustomerReg.ClientRegId == input.Id).ToList();
                if (input.RegIds != null && input.RegIds.Count > 0)
                {
                    jyyclistjb = jyyclistjb.Where(p => input.RegIds.Contains(p.CustomerRegID)).ToList();
                }

                var jyyclist = jyyclistjb.Select(p => p.SummarizeName).Distinct().ToList();


                string ycxdt = "0";
                string yccc = "0";
                string ycxp = "0";
                var cusSmumls = cusSmum.ToList();
                foreach (var jyyc in jyyclist)
                {

                    var IllName = jyyc;
                    var cusDpart = cusSmumls.Where(p =>
                    (!string.IsNullOrEmpty(p.DagnosisSummary) && p.DagnosisSummary.Contains(IllName)) ||
                    (!string.IsNullOrEmpty(p.CharacterSummary) && p.CharacterSummary.Contains(IllName))).Select(p => new
                    {
                        p.CustomerRegId,
                        p.DepartmentBMId,
                        p.DepartmentName,
                        p.DepartmentOrder
                    }).ToList();
                    if (cusDpart != null && cusDpart.Count() > 0)
                    {
                        YCXMDto yCXM1 = new YCXMDto();
                        yCXM1.DepartId = cusDpart.FirstOrDefault().DepartmentBMId.Value;
                        yCXM1.GroupName = cusDpart.FirstOrDefault().DepartmentName;
                        yCXM1.IllName = IllName;
                        yCXM1.OrderNum = cusDpart.FirstOrDefault().DepartmentOrder;
                        yCXM1.Count = cusDpart.Select(p => p.CustomerRegId).Distinct().Count();
                        cusdepartSumlist.Add(yCXM1);
                        if (yCXM1.GroupName == "心电图")
                        {
                            ycxdt = yCXM1.Count.ToString();
                        }
                        if (yCXM1.GroupName == "彩超")
                        {
                            yccc = yCXM1.Count.ToString();
                        }
                        if (yCXM1.GroupName == "胸片")
                        {
                            ycxp = yCXM1.Count.ToString();
                        }
                    }
                }
                ycst.AddRange(cusdepartSumlist);
                ycst = ycst.OrderBy(p => p.GroupName).ThenBy(p => p.OrderNum).ToList();
                outPut.YCXM = ycst;
                #endregion
                #region 异常项目明细
                YCXMDeTailDto yCXMDeTail = new YCXMDeTailDto();
                var xyyc = queycst.Where(p => (p.ItemName == "收缩压" || p.ItemName == "舒张压")).Select(p => p.CustomerRegId).Distinct().Count();
                var xypg = queycst.Where(p => (p.ItemName == "收缩压" || p.ItemName == "舒张压") && p.Symbol.Contains("H")).Select(p => p.CustomerRegId).Distinct().Count();
                var xypd = queycst.Where(p => (p.ItemName == "收缩压" || p.ItemName == "舒张压") && p.Symbol.Contains("L")).Select(p => p.CustomerRegId).Distinct().Count();
                yCXMDeTail.XYYC = xyyc.ToString();
                yCXMDeTail.XYPG = xypg.ToString();
                yCXMDeTail.XYPD = xypd.ToString();
                var XDTYC = cusdepartSumlist.Where(p => p.GroupName.Contains("心电图")).Count();
                yCXMDeTail.XDTYC = XDTYC.ToString();
                var dct = queycst.Where(p => p.DepartmentBM.Name.Contains("电测听")).Count();
                var dctgp = queycst.Where(p => p.DepartmentBM.Name.Contains("电测听") &&
                 p.ItemName.Contains("高频听阈")).Count();
                var dctyp = queycst.Where(p => p.DepartmentBM.Name.Contains("电测听") &&
              p.ItemName.Contains("语频高频听阈")).Count();
                yCXMDeTail.DCTYC = dct.ToString();
                yCXMDeTail.DCTGP = dctgp.ToString();
                yCXMDeTail.DCTYP = dctyp.ToString();
                var cc = cusSmumls.Where(p => p.DepartmentName.Contains("彩超")).Select(p =>
                p.CustomerRegId).Distinct().Count();
                yCXMDeTail.CCRS = cc.ToString();
                yCXMDeTail.CCYC = yccc.ToString();

                yCXMDeTail.XPYC = ycxp.ToString();
                var fgn = queycst.Where(p => p.DepartmentBM.Name.Contains("肺功能")).Count();
                yCXMDeTail.FGNYC = fgn.ToString();
                var jyycrs = queycst.Where(p => p.DepartmentBM.Category.Contains("检验")).
                     Select(p => p.ItemSum.Contains(p.ItemName) ? p.ItemSum : (p.ItemName + p.ItemSum)).Distinct().ToList();
                List<JYKDto> JYKs = new List<JYKDto>();
                string sysyc = "";
                foreach (var jyyc in jyycrs)
                {
                    JYKDto jYK = new JYKDto();
                    var sumAd = jyyclistjb.FirstOrDefault(p => jyyc.Contains(p.SummarizeName));
                    if (sumAd != null)
                    {
                        jYK.Advice = sumAd.Advice;
                        jYK.IllName = sumAd.SummarizeName;
                        jYK.Remark = sumAd.SummarizeAdvice?.ClientAdvice;
                        JYKs.Add(jYK);
                        string sysjc = "  " + jYK.IllName + ":" + jYK.Advice + "\r\n";
                        sysyc = sysyc + sysjc;
                    }
                }
                yCXMDeTail.jYKs = JYKs;
                yCXMDeTail.SYSJC = sysyc;
                outPut.YCXMDetail = new List<YCXMDeTailDto>();
                outPut.YCXMDetail.Add(yCXMDeTail);
                #endregion
                #region 复查
                var occcusFC = _CustomerHazardSum.GetAll().Where(p => p.CustomerRegBM.ClientRegId == input.Id
                && p.Conclusion.Contains("复查")).Select(p => new FCMDDto
                {
                    RegId = p.CustomerRegBMId,
                    Age = p.CustomerRegBM.Customer.Age,
                    CLYJ = p.Advise,
                    GZ = p.CustomerRegBM.TypeWork,
                    JHNL = p.CustomerRegBM.InjuryAge,
                    Name = p.CustomerRegBM.Customer.Name,
                    SEX = p.CustomerRegBM.Customer.Sex == 1 ? "男" : "女",
                    TJH = p.CustomerRegBM.CustomerBM,
                    WHYS = p.CustomerRegBM.RiskS,
                    YY = p.Description
                }).ToList();
                if (input.RegIds != null && input.RegIds.Count > 0)
                {
                    occcusFC = occcusFC.Where(p => p.RegId.HasValue && input.RegIds.Contains(p.RegId.Value)).ToList();
                }
                outPut.FCRS = occcusFC;
                #endregion
                //检查项目
                #region MyRegion
                var jlque = _CustomerHazardSum.GetAll().Where(p => p.CustomerRegBM.ClientRegId == input.Id);
                if (input.RegIds != null && input.RegIds.Count > 0)
                {
                    jlque = jlque.Where(p => p.CustomerRegBMId.HasValue && input.RegIds.Contains(p.CustomerRegBMId.Value));
                }
                var jl = jlque.Select(p =>
                     new { p.CustomerRegBM.CustomerBM, p.Conclusion }).ToList();

                var cusItemsque = _CustomerRegItem.GetAll().Where(p => p.CustomerRegBM.ClientRegId == input.Id
                   && p.ProcessState == (int)ProjectIState.Complete &&
                   p.CustomerItemGroupBM.IsAddMinus != 3 &&
                   (p.ItemName == "收缩压" || p.ItemName == "舒张压"));
                if (input.RegIds != null && input.RegIds.Count > 0)
                {
                    cusItemsque = cusItemsque.Where(p => input.RegIds.Contains(p.CustomerRegId));
                }
                List<JKJCJGDto> cusItems = cusItemsque.Select(
                    p => new JKJCJGDto
                    {

                        MC = p.ItemName,
                        JL = p.ItemResultChar,
                        Depart = p.CustomerRegBM.WorkName,
                        GZ = p.CustomerRegBM.TypeWork,
                        WHYS = p.CustomerRegBM.RiskS,
                        JHGL = p.CustomerRegBM.InjuryAge,
                        TJBH = p.CustomerRegBM.CustomerBM,
                        Name = p.CustomerRegBM.Customer.Name,
                        IDCard = p.CustomerRegBM.Customer.IDCardNo,
                        TJRQ = p.CustomerRegBM.LoginDate,
                        TJLX = p.CustomerRegBM.PostState
                    }).ToList();
                var TJcusSmumque = _CustomerDepSummary.GetAll().Where(p => p.CustomerReg.ClientRegId == input.Id
                && p.DepartmentBMId != null && (p.DepartmentBM.Name.Contains("心电图") || p.DepartmentBM.Name.Contains("彩超")
                || p.DepartmentBM.Name.Contains("超声") ||
                p.DepartmentBM.Name.Contains("放射") ||
                p.DepartmentBM.Name.Contains("电测听")));
                if (input.RegIds != null && input.RegIds.Count > 0)
                {
                    TJcusSmumque = TJcusSmumque.Where(p => p.CustomerRegId.HasValue && input.RegIds.Contains(p.CustomerRegId.Value));
                }

                List<JKJCJGDto> TJcusSmum = TJcusSmumque.Select(
                    p => new JKJCJGDto
                    {

                        MC = p.DepartmentName,
                        JL = p.DagnosisSummary == null ? p.CharacterSummary :
                        p.DagnosisSummary == "" ? p.CharacterSummary : p.DagnosisSummary,
                        Depart = p.CustomerReg.WorkName,
                        GZ = p.CustomerReg.TypeWork,
                        WHYS = p.CustomerReg.RiskS,
                        JHGL = p.CustomerReg.InjuryAge,
                        TJBH = p.CustomerReg.CustomerBM,
                        Name = p.CustomerReg.Customer.Name,
                        IDCard = p.CustomerReg.Customer.IDCardNo,
                        TJRQ = p.CustomerReg.LoginDate,
                        TJLX = p.CustomerReg.PostState
                    }).ToList();


                List<JKJCJGDto> cusItemnew = new List<JKJCJGDto>();
                cusItemnew.AddRange(cusItems);
                cusItemnew.AddRange(TJcusSmum);
                var cusRegIds = cusItemnew.Select(p => p.TJBH).Distinct().ToList();
                List<JKJCJGDto> cusItemCOut = new List<JKJCJGDto>();
                foreach (var TJBH in cusRegIds)
                {
                    var cusjl = cusItemnew.Where(p => p.TJBH == TJBH).ToList();
                    JKJCJGDto jKJCJG = new JKJCJGDto();

                    jKJCJG.Depart = cusjl.FirstOrDefault().Depart;
                    jKJCJG.GZ = cusjl.FirstOrDefault().GZ;
                    jKJCJG.WHYS = cusjl.FirstOrDefault().WHYS;
                    jKJCJG.JHGL = cusjl.FirstOrDefault().JHGL;
                    jKJCJG.TJBH = cusjl.FirstOrDefault().TJBH;
                    jKJCJG.Name = cusjl.FirstOrDefault().Name;
                    jKJCJG.IDCard = cusjl.FirstOrDefault().IDCard;
                    jKJCJG.TJRQ = cusjl.FirstOrDefault().TJRQ;
                    jKJCJG.TJLX = cusjl.FirstOrDefault().TJLX;
                    jKJCJG.CC = cusjl.FirstOrDefault(p => p.MC.Contains("彩超") || p.MC.Contains("超声"))?.JL;
                    jKJCJG.dct = cusjl.FirstOrDefault(p => p.MC.Contains("电测听"))?.JL;
                    jKJCJG.xp = cusjl.FirstOrDefault(p => p.MC.Contains("放射"))?.JL;
                    jKJCJG.xdt = cusjl.FirstOrDefault(p => p.MC.Contains("心电图"))?.JL;
                    jKJCJG.SSY = cusjl.FirstOrDefault(p => p.MC.Contains("收缩压"))?.JL;
                    jKJCJG.SZY = cusjl.FirstOrDefault(p => p.MC.Contains("舒张压"))?.JL;
                    var cusoccjl = occcusSum.FirstOrDefault(p => p.CustomerRegBM != null && p.CustomerRegBM.CustomerBM == TJBH);
                    if (cusoccjl != null)
                    {
                        jKJCJG.JL = cusoccjl.Conclusion;
                    }
                    cusItemCOut.Add(jKJCJG);
                }

                outPut.JCJG = cusItemCOut;
                #endregion




                return outPut;
            }
            catch (Exception ex)
            {
                string ss = ex.Message;
                throw new FieldVerifyException("异常！", ss);

            }
        }
    }
}